import { msg } from '../../components/notice/notice';
import { isMember } from '/imports/models/ChannelMembers';

Template.exploreChannelCard.helpers({
  isOwnerOrJoined: function() {
    const current = Meteor.userId();
    if (current == Template.instance().data.channel.owner.id) {
      return true;
    }

    return isMember(Template.instance().data.channel._id, current);
  }
});

Template.exploreChannelCard.events({
  'click .join-channel-button'(event, instance) {
    let options = {
      _id: instance.data.channel._id,
      channelId: instance.data.channel.channelId,
      policy: instance.data.channel.policy,
      owner: instance.data.channel.owner
    };

    Meteor.call('joinChannel', options, (error, result) => {
      if (result == 'join_success') {
        msg({content: '成功加入，正在跳转', time: 1000});
        setTimeout(() => {
          Router.go('channel', {channelId: instance.data.channel.channelId});
        }, 1000);
      }

      if (result == 'need_allow') {
        msg({content: '你的申请已经发送成功了'});
      }

      if (!result) {
        return;
      }
    });
  },
  'click .open-channel-button'(event, instance) {
    Router.go('channel', {channelId: instance.data.channel.channelId});
  }
});
